package com.rookie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.CollectionUtils;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.rookie.entity.Menu;
import com.rookie.common.dto.MenuDto;
import com.rookie.entity.User;
import com.rookie.mapper.MenuMapper;
import com.rookie.service.MenuService;
import com.rookie.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * service实现类
 */
@Service
public class MenuServiceImpl extends ServiceImpl<MenuMapper, Menu> implements MenuService {

    @Autowired
    UserService userService;
    @Autowired
    MenuMapper menuMapper;

    /**
     * 查询当前用户的导航栏
     */
    @Override
    public List<MenuDto> getCurrentUserNav() {
        String username = (String) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
        User user = userService.getUserByUsername(username);
        List<Long> menuIds = menuMapper.getMenuIdsByUid(user.getId());
        List<Menu> menuList = this.listByIds(menuIds);
        // 菜单列表转换成树形菜单
        List<Menu> treeMenu = menuTableToTreeMenu(menuList);
        // 菜单树转成DTO
        return this.convert(treeMenu);
    }

    /**
     * 查询树形菜单
     */
    @Override
    public List<Menu> treeMenu() {
        List<Menu> menuList = this.list(new LambdaQueryWrapper<Menu>().orderByAsc(Menu::getOrderNum));
        return this.menuTableToTreeMenu(menuList);
    }

    /**
     * 菜单列表转换成树形菜单
     */
    private List<Menu> menuTableToTreeMenu(List<Menu> menuList) {
        Map<Long, List<Menu>> collect = menuList.stream().filter(menu -> menu.getParentId() != 0).collect(Collectors.groupingBy(Menu::getParentId));
        menuList.parallelStream().forEach(menu -> menu.setChildren(collect.get(menu.getId())));
        return menuList.stream().filter(menu -> menu.getParentId() == 0).collect(Collectors.toList());
    }

    /**
     * 菜单树转成DTO
     */
    private List<MenuDto> convert(List<Menu> menuTree) {
        List<MenuDto> menuTreeDto = new ArrayList<>();
        menuTree.forEach(menu -> {
            MenuDto menuDto = new MenuDto();
            menuDto.setId(menu.getId());
            menuDto.setName(menu.getPerms());
            menuDto.setTitle(menu.getName());
            menuDto.setIcon(menu.getIcon());
            menuDto.setComponent(menu.getComponent());
            menuDto.setPath(menu.getPath());
            if (CollectionUtils.isNotEmpty(menu.getChildren())) menuDto.setChildren(convert(menu.getChildren()));
            menuTreeDto.add(menuDto);
        });
        return menuTreeDto;
    }

}




